<template>
  <div class="watermark-container" :style="containerStyle">
    <canvas ref="watermarkCanvas" :width="canvasWidth" :height="canvasHeight"></canvas>
  </div>
</template>

<script>
export default {
  name: 'Watermark',
  props: {
    text: {
      type: String,
      default: 'AI生成内容仅供参考'
    },
    fontSize: {
      type: Number,
      default: 12
    },
    color: {
      type: String,
      default: 'rgba(177, 176, 176, 0.5)'
    },
    angle: {
      type: Number,
      default: -40
    },
    density: {
      type: Number,
      default: 120
    }
  },
  data() {
    return {
      canvasWidth: 300,
      canvasHeight: 200
    }
  },
  computed: {
    containerStyle() {
      return {
        position: 'absolute',
        top: 0,
        left: 0,
        width: '100%',
        height: '100%',
        pointerEvents: 'none',
        zIndex: 1,
        overflow: 'hidden'
      }
    }
  },
  mounted() {
    this.drawWatermark()
    this.resizeCanvas()
    window.addEventListener('resize', this.resizeCanvas)
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.resizeCanvas)
  },
  watch: {
    text() {
      this.drawWatermark()
    },
    fontSize() {
      this.drawWatermark()
    },
    color() {
      this.drawWatermark()
    },
    angle() {
      this.drawWatermark()
    },
    density() {
      this.drawWatermark()
    }
  },
  methods: {
    resizeCanvas() {
      const container = this.$el.parentElement
      if (container) {
        this.canvasWidth = container.offsetWidth
        this.canvasHeight = container.offsetHeight
        this.$nextTick(() => {
          this.drawWatermark()
        })
      }
    },
    drawWatermark() {
      const canvas = this.$refs.watermarkCanvas
      if (!canvas) return

      const ctx = canvas.getContext('2d')
      ctx.clearRect(0, 0, this.canvasWidth, this.canvasHeight)

      // 设置字体和颜色
      ctx.font = `${this.fontSize}px Arial, sans-serif`
      ctx.fillStyle = this.color
      ctx.textAlign = 'center'
      ctx.textBaseline = 'middle'

      // 计算水印间距
      const spacing = this.density
      const cols = Math.ceil(this.canvasWidth / spacing) + 1
      const rows = Math.ceil(this.canvasHeight / spacing) + 1

      // 绘制水印
      for (let i = 0; i < rows; i++) {
        for (let j = 0; j < cols; j++) {
          const x = j * spacing
          const y = i * spacing

          ctx.save()
          ctx.translate(x, y)
          ctx.rotate((this.angle * Math.PI) / 180)
          ctx.fillText(this.text, 0, 0)
          ctx.restore()
        }
      }
    }
  }
}
</script>

<style scoped>
.watermark-container {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  pointer-events: none;
  z-index: 1;
  overflow: hidden;
}

.watermark-container canvas {
  display: block;
  width: 100%;
  height: 100%;
}
</style>
